﻿using UnityEngine.UIElements;
using GraphProcessor;
using UnityEditor;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class LevelServiceToolbarView : ToolbarView
    {
        public LevelServiceToolbarView(BaseGraphView graphView) : base(graphView)
        {
        }

        protected override void AddButtons()
        {
            AddButton("Center", graphView.ResetPositionAndZoom);
            
            bool conditionalProcessorVisible = graphView.GetPinnedElementStatus<LevelServiceProcessorView>() != DropdownMenuAction.Status.Hidden;
            AddToggle("Show LevelService Processor", conditionalProcessorVisible, (v) => graphView.ToggleView<LevelServiceProcessorView>());
                        
            AddButton("Show In Project", () => EditorGUIUtility.PingObject(graphView.graph), false);
            
            graphView.ClosePinned<PrefabProcessorView>();
        }
    }

    public class LevelServiceProcessorView : PinnedElementView
    {
        LevelServiceProcessor processor;

        public LevelServiceProcessorView() => title = "LevelService Processor";

        protected override void Initialize(BaseGraphView graphView)
        {
            processor = new LevelServiceProcessor(graphView.graph);

            graphView.computeOrderUpdated += processor.UpdateComputeOrder;

            Button runButton = new Button(OnPlay) { name = "ActionButton", text = "导出" };
            Button refreshButton = new Button(OnRefresh) { name = "ActionButton", text = "刷新" };
            Button clearButton = new Button(OnClear) { name = "ActionButton", text = "Clear" };
            Button packageButton = new Button(ExportAll) { name = "ActionButton", text = "全部导出" };
            Button syncButton = new Button(SyncExecution) { name = "ActionButton", text = "同步执行" };
            
            content.Add(runButton);
            content.Add(refreshButton);
            content.Add(clearButton);
            content.Add(packageButton);
            content.Add(syncButton);
        }

        void OnPlay()
        {
            processor.Run();
            LevelServiceBlackboard.Instance.Package(AssetDatabase.GetAssetPath(this.processor.Graph));
        }

        void OnRefresh()
        {
            processor.Refresh();
        }

        void OnClear()
        {
            LevelServiceBlackboard.Instance.Clear();
        }
        
        void ExportAll()
        {
            LevelServiceBlackboard.Instance.PackageAll();
        }

        void SyncExecution()
        {
            processor.Run();
            LevelServiceBlackboard.Instance.SyncExecutionOnGraph();
        }
    }
}